#!/usr/bin/env bash

s=$(which sleep)

t='<?xml version="1.0" standalone="yes"?>
<tp2package>
<name>test_sleep_pkg</name>
<version>1.0.0</version>
<description>Test package for sleep</description>
<files>'

t2='</files>
</tp2package>'

dd=$(dirname $s)
flist=$(ls $dd/s*)

o=$(whoami)
g=$(id | perl -ne '/.*\((.*?)\).*\((.*?)\).*/; print $2')

if [[ -d tt ]]
then
	rm -rf tt
fi

mkdir tt 
exec >tt/test_01.xml
cp $dd/s* tt
echo "$t"
for f in $flist
do
	echo "<file perms=\"755\" owner=\"$o\" group=\"$g\">$(basename $f)</file>";
done
echo "$t2"
 
cd tt
tp2pkg --overwrite --config test_01.xml --verbose --repos /tmp || exit 1

# Remove tt_test_01 namespace if it exists

tp2remove_ns --namespace tt_test_01 --leave

mkdir pkg_root

# Create the new namespace.
../../../bin/tp2make_ns --owner $o --root $PWD/pkg_root --name tt_test_01 --nosqlite || exit 1 

# Install the package.
../../../bin/tp2install --namespace tt_test_01 --pkg test_sleep_pkg --verbose --repos /tmp --reinstall  --force
# [[ $? -ne 0 ]] && exit 1

# Run the sleep command ..

nohup $PWD/pkg_root/sleep 30 &

# Attempt to remove the package (should leave the sleep command in place)
../../../bin/tp2remove --namespace tt_test_01 --pkg test_sleep_pkg --verbose
[[ $? -ne 0 ]] && exit 1

# Test the "rm on reboot" file exists and that 
# it contains the 'sleep.remove.$$' file.

if [[ ! -f 'pkg_root/sleep.remove.$$' ]]
then
	echo "Sleep file removed ok."
	exit 0
fi
if [[ ! -f "/var/adm/tp2/ns/tt_test_01/pkg/rm on reboot" ]]
then
	echo "Failed: rm on reboot file does not exist."
	exit 1
fi

if [[ "$(cat "/var/adm/tp2/ns/tt_test_01/pkg/rm on reboot")" != 'sleep.remove.$$' ]]
then
	echo "Failed: Contents of 'rm on reboot' not as expected."
	exit 1
fi

# Normal sleep - to wait to a suitable point to clean-up!!

sleep 35
../../../bin/tp2boot --verbose --namespace tt_test_01

if [[ -f "/var/adm/tp2/ns/tt_test_01/pkg/rm on reboot" ]]
then
	echo "Failed: rm on reboot file should not exist."
	exit 1
fi

if [[ -f 'pkg_root/sleep.remove.$$' ]]
then
	echo "Failed: sleep temporary file is still in place." ]]
	exit 1
fi

echo ""
echo "Test passed successfully."
exit 0


